import request from '../../../utils/request'
Page({
  data: {
    serviceTags: [
        {
          id: 1,
          name: "慢病护理",
          active: false
        },
        {
          id: 2,
          name: "颈椎病",
          active: false
        },
        {
          id: 3,
          name: "心脑血管病",
          active: false
        },
        // 可以继续添加更多的标签项
      ]
  },

  onLoad: function(options) {
    this.getmydocTeam()
        .then(teamId=>this.getDoctorIdTeamInfoByTeamID(teamId))
        .then(({ docIds, teamInfo })=>{
            // 将docIds和teaminfo放入this
            this.setData({
                docIds:docIds,
                teamInfo:teamInfo
            })
            this.getInstitution(teamInfo)
            .then(institutionInfo=>{
                // 将所属机构放入this
                this.setData({
                    institutionInfo:institutionInfo
                })
            })
            this.getDoctor(docIds)
            .then(doctors=>{
                this.setData({
                    doctors:doctors
                })
            })
        })
  },



//获取签约teamId
  getmydocTeam(){
      return new Promise((resolve,reject)=>{
        let userId = wx.getStorageSync('userid')
        let url = `contractlog/contractlog/selectByUserId/${userId}`
        request({
            url:url,
            method:'GET',
            success(res){
        //       console.log("aaa",res.data);
              let contract = res.data
        //       console.log( 'contract->',contract[0]);
        //       console.log( 'teamid->',contract[0].team);
              let teamId = contract[0].team
        //       console.log( 'team->',teamId);
              resolve(teamId)
            },
            fail(error){
                reject(error)
            }
          });
      })
  },
// 通过teamId从中间表获取docIds集合以及从team表中获取teaminfo对象
getDoctorIdTeamInfoByTeamID(teamId) {
    let url1 = `sysmanagement/doctorteam/teamid/${teamId}`;
    let url2 = `system/team/teamid/${teamId}`;

    const getDocIdsPromise = new Promise((resolve, reject) => {
      request({
        url: url1,
        method: 'GET',
        success(res) {
                // console.log("11111",res.data.data);
          let docIds = res.data.data.map(item => item.doctorId);
          resolve(docIds);
        },
        fail(error) {
          reject(error);
        }
      });
    });

    const getTeamInfoPromise = new Promise((resolve, reject) => {
      request({
        url: url2,
        method: 'GET',
        success(res) {
          let teamInfo = res.data.data;
          resolve(teamInfo);
        },
        fail(error) {
          reject(error);
        }
      });
    });

    return Promise.all([getDocIdsPromise, getTeamInfoPromise])
     .then(([docIds, teamInfo]) => {
        return { docIds, teamInfo };
      });
  },
  //获取团队所属机构
  getInstitution(teamInfo){
    //   console.log("eeeeee",teamInfo);
      return new Promise((resolve,reject)=>{
          let institutionId = teamInfo.institutionid
          let url = `system/institution/${institutionId}`
          request({
              url:url,
              method:'GET',
              success(res){
                  let institutionInfo = res.data.data
                //   console.log("Institution",res.data.data);
                resolve(institutionInfo)
              },fail(error){
                  reject(error)
              }
          })
      })
  },
  //获取团队所属医生
  getDoctor(docIds) {
    // console.log("uuuuuuu", docIds);
    const doctors = [];
    return new Promise((resolve, reject) => {
        const fetchDoctors = async () => {
            for (const id of docIds) {
                const url = `system/doctor/${id}`;
                await new Promise((innerResolve, innerReject) => {
                    request({
                        url: url,
                        method: 'GET',
                        success(res) {
                            // console.log("ooooooo",res.data.data);
                            doctors.push(res.data.data);
                            innerResolve();
                        },
                        fail(error) {
                            innerReject(error);
                        }
                    });
                });
            }
            // console.log("pppp",doctors);
            resolve(doctors);
        };
        fetchDoctors().catch(reject);
    });
},
  goBack: function() {
    wx.navigateBack();
  },

  refresh: function() {
    // 刷新页面数据
    // this.loadTeamInfo(this.data.teamInfo.id);
  },

  selectTag: function(e) {
    const tagId = e.currentTarget.dataset.id;
    const tags = this.data.serviceTags.map(tag => ({
      ...tag,
      active: tag.id === tagId
    }));
    
    this.setData({
      serviceTags: tags
    });

    // 可以根据选中的标签筛选医生列表
    // this.filterDoctors(tagId);
  },

  navigateToDoctor: function(e) {
    const doctorId = e.currentTarget.dataset.id;
    //将teamInfo对象和institutioninfo对象转成str传给另一个页面
    const teamInfoStr = JSON.stringify(this.data.teamInfo);
    const institutionInfoStr = JSON.stringify(this.data.institutionInfo);
    wx.navigateTo({
      url: `/pages/profile/doctordetail/doctordetail?id=${doctorId}&teamInfo=${encodeURIComponent(teamInfoStr)}&institutionInfo=${encodeURIComponent(institutionInfoStr)}`
    });
  },

  loadTeamInfo: function(teamId) {
    调用API获取团队信息
    wx.request({
      url: `your-api-url/team/${teamId}`,
      success: (res) => {
        this.setData({
          teamInfo: res.data.teamInfo,
          doctors: res.data.doctors
        });
      }
    });
  },

  // filterDoctors: function(tagId) {
  //   // 根据选中的服务标签筛选医生列表
  //   // 这里可以调用API或者本地筛选
  // }
}); 